<template>
	<div class="div-user-sum">
		<div class="div-top">
			<span>题库管理</span>
		</div>
		<span class="search_label">题干:</span>
		<el-input v-model='searchForm.question' placeholder="请输入题干" style="width:207px;margin-left: 10px" clearable></el-input>
		<span class="search_label">题型:</span>
		<el-select v-model='searchForm.questionType' placeholder="请选择题型" @change='currentChange(1)' style="width:207px;margin-left: 10px" clearable>
			<el-option v-for="item in questionTypes" :key="item.value" :label="item.name" :value="item.value">
			</el-option>
		</el-select>
		<span class="search_label">难度:</span>
		<el-select v-model='searchForm.difficulty' placeholder="试题难度" @change='currentChange(1)' style="width:207px;margin-left: 10px" clearable>
			<el-option v-for="item in difficultys" :key="item.value" :label="item.name" :value="item.value">
			</el-option>
		</el-select>
		<span class="search_label">试题类型:</span>
		<el-select v-model='searchForm.questionUse' placeholder="试题类型" @change='currentChange(1)' style="width:207px;margin-left: 10px" clearable>
			<el-option v-for="item in questionUses" :key="item.value" :label="item.name" :value="item.value">
			</el-option>
		</el-select>
		<span class="search_label">所属专业:</span>
		<el-select v-model='searchForm.majorId' placeholder="请选择专业" @change='currentChange(1)' style="width:207px;margin-left: 10px" clearable>
			<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
			</el-option>
		</el-select>
		<el-button type="primary" @click="currentChange(1)" style="margin-left: 5px">搜索</el-button>
		<br />
		<br />
		<el-button type="primary" @click="addShow = true" style="margin-left: 5px">添加试题</el-button>
		<el-button type="success" @click="uploadShow = true" style="margin-left: 5px">导入试题</el-button>
		<el-button type="danger" @click="toTopicsError" style="margin-left: 5px">导入出错试题</el-button>
		<el-button type="primary" @click="openDown()" style="margin-left: 5px">导出试题</el-button>
		<el-button type="success" @click="openScore()" style="margin-left: 5px">默认分值</el-button>
		<div class="topic_tables green_table" style="margin: 20px;">
			<el-table :data="dataList" border stripe @sort-change='sortChange' >
				<el-table-column prop="question" align="center" label="题干">
					<template slot-scope="scope">
						<span class="editor_box" v-html="scope.row.question"></span>
					</template>
				</el-table-column>
				<el-table-column prop="questionType" align="center" label="题型">
					<template slot-scope="scope">
						<span v-for='item in questionTypes' v-if="item.value == scope.row.questionType">{{item.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="difficulty" label="难度" align="center" sortable='custom'>
					<template slot-scope="scope">
						<span v-for='item in difficultys' v-if="item.value == scope.row.difficulty">{{item.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="questionUse" label="试题类型" align="center">
					<template slot-scope="scope">
						<span v-for='item in questionUses' v-if="item.value == scope.row.questionUse">{{item.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="majorName" label="所属专业" align="center">
				</el-table-column>
				<el-table-column prop="updateTime" label="创建时间" align="center" sortable='custom'>
				</el-table-column>
				<el-table-column label="操作" align="center" width='260'>
					<template slot-scope="scope">
						<el-button size='small' type='success' @click="openInfo(scope.row)">查看</el-button>
						<el-button size='small' type='primary' @click="openEdit(scope.row)">编辑</el-button>
						<el-button size='small' type='danger' @click="openDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div style="margin: 10px; text-align: center;">
			<el-pagination background @current-change="currentChange" :current-page="searchForm.pageNum" :page-size="searchForm.pageSize" layout="prev, pager, next, total, jumper" :total="searchForm.total">
			</el-pagination>
		</div>
		<el-dialog title="导入试题" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="addShow" width="1300px">
			<el-form :model="addForm" :rules="rules" ref='addForm'>
				<el-form-item prop="questionUse" label='试题类型：'>
					<div class="topic_type_selects">
						<div @click="selectType(item.value)" :class="addForm.questionUse == item.value?'active':''" class="topic_type_select  like_btn" v-for="item in questionUses">{{item.name}}</div>
					</div>
					<el-input v-show='false' v-model='addForm.questionUse'></el-input>
				</el-form-item>
				<el-form-item prop="majorId" label='所属专业：' style='position: relative;'>
					<el-select v-model='addForm.majorId' placeholder="请选择专业" clearable>
						<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<questioninput ref='questioninput' :form='addForm'></questioninput>
			<div slot="footer" class="dialog-footer">
				<el-button type="danger" @click="clearCheck(true)">取消</el-button>
				<el-button @click="clearCheck(false)">清空内容</el-button>
				<el-button type="primary" @click="beforeCheck">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="导入试题" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="uploadShow" width="720px">
			<el-form :model="uploadForm" :rules="rules" ref='uploadForm'>
				<el-form-item prop="questionUse" label='试题类型：'>
					<div class="topic_type_selects">
						<div @click="selectUpType(item.value)" :class="uploadForm.questionUse == item.value?'active':''" class="topic_type_select  like_btn" v-for="item in questionUses">{{item.name}}</div>
					</div>
					<el-input v-show='false' v-model='uploadForm.questionUse'></el-input>
				</el-form-item>
				<el-form-item prop="majorId" label='所属专业：' style='position: relative;'>
					<el-select v-model='uploadForm.majorId' placeholder="请选择专业" clearable>
						<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item prop="file">
					<div class="upload_box" :class="dragenterIng?'active':''" @click="clickElement($event, 'upload_folder')" @drop="handleFileDrop($event)" @dragleave="dragleave($event)" @dragenter="dragenter($event)" @dragover="stopEvent($event)">
						<div class="upload_boxinfo">
							<img src="@/assets/images/upload_boxicon.png" />
							<div class="upload_boxtext">
								<div class="upload_boxtextP1">将文件拖到此处</div>
								<div class="upload_boxtextP2">或单击以选择文件</div>
							</div>
						</div>
					</div>
					<div class="upload_file clearfix" v-if="uploadForm.uploadFile">
						<div class="upload_fileP1 text-ellipsis">
							{{uploadForm.uploadFile}}
							<div @click="deleteFile" class="upload_fileP1del" v-if="!uploadForm.uploadFlag">删除</div>
						</div>
						<div class="upload_fileP2" v-if="uploadForm.uploadFlag">
							<div class="upload_fileP2info" :style="getWidth"></div>
						</div>
					</div>
					<input ref="upload_folder" accept=".xls,.xlsx" type="file" style="display: none" @change="handleFileInput($event)" />
					<el-input v-show='false' v-model='uploadForm.url'></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="success" @click="downLoadExcel">下载excel模板</el-button>
				<el-button @click="clearUpCheck(true)">取 消</el-button>
				<el-button type="primary" @click="beforeUpCheck">确 定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="默认分值" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="scoreShow" width="720px">
			<div class="topic_dialog_tip">该页面所设置的分值规则，将同时应用于作业和试卷中</div>
			<el-form :model="scoreForm" :rules="rules" ref='scoreForm'>
				<el-form-item label="单选题" :label-width="'80px'" prop="singleScore">
					<el-col :span="22">
						<el-input v-model="scoreForm.singleScore" placeholder="请输入分值"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="多选题" :label-width="'80px'" prop="multipleScore">
					<el-col :span="22">
						<el-input v-model="scoreForm.multipleScore" placeholder="请输入分值"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="判断题" :label-width="'80px'" prop="judgeScore">
					<el-col :span="22">
						<el-input v-model="scoreForm.judgeScore" placeholder="请输入分值"></el-input>
					</el-col>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="clearScCheck(true)">取 消</el-button>
				<el-button type="primary" @click="beforeScCheck">确 定</el-button>
			</div>
		</el-dialog>
		<el-drawer :visible.sync="topicShow" :with-header="false" :size='450'>
			<div class="topic_info">
				<div class="topic_info_title">试题详情</div>
				<div class="topic_info_body beautifulScroll" v-if='topicShow'>
					<div class="topic_info_type">
						所属专业：【{{openTopic.majorName}}】
					</div>
					<questionview :readonly='true' :allshow='true' :showanswer='true' :form="openTopic"></questionview>
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<script>
	import questionview from "@/components/question/questionview.vue"
	import questioninput from "@/components/question/questioninput.vue"
	import { putProgress } from "@/utils/oss.js"
	import { teacherInfo } from "@/api/teacher.js"
	import { majorList } from "@/api/major.js"
	import { selectTopicTemplate, saveTopicTemplate, updateTopicTemplate } from "@/api/topicScoreTemplate.js"
	import { topicList, saveTopic, updateTopic, removeTopic, selectTopicDetail, topicExport, selectTopicList, selectQuestionCountByType, importTopic, downloadTemplate } from "@/api/topic.js"
	export default {
		components: {
			questionview,
			questioninput
		},
		data() {
			var checkNumber = (rule, value, callback) => {
				if(!value) {
					return callback(new Error('请输入分值'));
				} else if(isNaN(Number(value))) {
					return callback(new Error('请输入数字'));
				} else if(!Number.isInteger(Number(value))) {
					return callback(new Error('请输入整数'));
				} else {
					return callback();
				}
			};
			return {
				dataList: [],
				majors: [],
				topicShow: false,
				openTopic: {},
				scoreShow: false,
				scoreEdited: false,
				scoreForm: {
					'singleScore': '',
					'multipleScore': '',
					'judgeScore': '',
				},
				dragenterIng: false,
				uploadShow: false,
				uploadForm: {
					questionUse: '',
					file: '',
					majorId: '',
					uploadFile: '',
					uploadFlag: false,
					uploadPress: 0,
				},
				topicId: '',
				addShow: false,
				addForm: {
					questionUse: '',
					difficulty: '',
					analysis: '',
					questionType: '',
					question: '',
					options: '',
					optionsArr: [],
					answer: '',
					answers: [],
					majorId: '',
				},
				rules: {
					questionUse: [{
						required: true,
						message: '请选择试题类型'
					}],
					file: [{
						required: true,
						message: '请上传文件'
					}],
					majorId: [{
						required: true,
						message: '请选择所属专业'
					}],
					singleScore: [{
						required: true,
						message: '请输入分值'
					}, {
						validator: checkNumber,
					}],
					multipleScore: [{
						required: true,
						message: '请输入分值'
					}, {
						validator: checkNumber,
					}],
					judgeScore: [{
						required: true,
						message: '请输入分值'
					}, {
						validator: checkNumber,
					}],
				},
				searchForm: {
					pageNum: 1,
					pageSize: 8,
					total: 0,
					question: '',
					questionType: '',
					difficulty: '',
					questionUse: '',
					orderBy: 'updateTime',
					ascDesc: 'desc',
					majorId: '',
				},
				questionTypes: [{
					name: '单选题',
					value: 'SINGLE'
				}, {
					name: '多选题',
					value: 'MULTIPLE'
				}, {
					name: '判断题',
					value: 'JUDGE'
				}],
				difficultys: [{
					name: '简单',
					value: 'SIMPLE'
				}, {
					name: '中等',
					value: 'MEDIUM'
				}, {
					name: '困难',
					value: 'DIFFICULTY'
				}],
				questionUses: [{
					name: '作业试题',
					value: '1'
				}, {
					name: '考核试题',
					value: '2'
				}],
			}
		},
		computed: {
			getWidth() {
				return "width:" + this.uploadForm.uploadPress + "%;"
			},
		},
		created() {
			this.getinfo();
			this.getMajors();
		},
		mounted() {

		},
		methods: {
			downLoadExcel() {
				downloadTemplate()
			},
			toTopicsError() {
				this.$router.push({
					name: 'topicserror'
				})
			},
			beforeScCheck() {
				if(this.postData) {
					return
				}
				this.postData = true;
				setTimeout(() => {
					this.postData = false;
				}, 1000)
				var that = this;
				this.$refs.scoreForm.validate(valid => {
					if(valid) {
						if(this.scoreEdited) {
							updateTopicTemplate(this.scoreForm).then(res => {
								if(res.code == '200') {
									this.$message({
										type: 'success',
										message: res.message
									});
									this.clearScCheck(true)
								} else {
									this.$message({
										type: 'error',
										message: res.message
									});
								}
							})
						} else {
							var data = Object.assign({}, this.scoreForm, {
								type: 2,
							})
							saveTopicTemplate(data).then(res => {
								if(res.code == '200') {
									this.$message({
										type: 'success',
										message: res.message
									});
									this.clearScCheck(true)
								} else {
									this.$message({
										type: 'error',
										message: res.message
									});
								}
							})
						}
					}
				})
			},
			openScore() {
				this.scoreEdited = false;
				selectTopicTemplate().then(res => {
					if(res.code == '200') {
						this.scoreForm = res.data;
						if(res.data.type == 2) {
							this.scoreEdited = true;
						}
						this.scoreShow = true;
					}
				})
			},
			clearScCheck(flag) {
				this.scoreForm = {
					'singleScore': '',
					'multipleScore': '',
					'judgeScore': '',
				}
				this.$nextTick(() => {
					this.$refs.scoreForm.clearValidate();
					if(flag) {
						this.scoreShow = false;
					}
				})
			},
			beforeUpCheck() {
				if(this.postData) {
					return
				}
				this.postData = true;
				setTimeout(() => {
					this.postData = false;
				}, 1000)
				this.$refs.uploadForm.validate(valid => {
					if(valid) {
						var formData = new FormData();
						formData.append("majorId", this.uploadForm.majorId);
						formData.append("file", this.uploadForm.file);
						formData.append("questionUse", this.uploadForm.questionUse);
						importTopic(formData).then(res => {
							if(res.code == '200') {
								this.$message({
									type: 'success',
									message: res.message
								})
								this.clearUpCheck(true);
								this.currentChange(1);
							} else {
								this.$message({
									type: 'error',
									message: res.message
								})
							}
						})
					}
				});
			},
			clearUpCheck(flag) {
				if(this.uploadForm.uploadFlag) {
					this.$message({
						type: "error",
						message: '请等待上传完成！'
					})
					return
				}
				this.uploadForm.questionUse = '';
				this.uploadForm.file = '';
				this.uploadForm.uploadFile = '';
				this.uploadForm.uploadFlag = false;
				this.uploadForm.uploadPress = 0;
				this.$nextTick(() => {
					this.$refs.uploadForm.clearValidate();
					if(flag) {
						this.uploadShow = false;
					}
				})
			},
			deleteFile() {
				this.uploadForm.file = '';
				this.uploadForm.uploadFile = '';
				this.uploadForm.uploadFlag = false;
				this.uploadForm.uploadPress = 0;
			},
			handleFileUpload(file) {
				this.dragenterIng = false;
				var filetype = file.name.substring(file.name.lastIndexOf('.') + 1);
				if(filetype == 'xls' || filetype == 'xlsx' || filetype == 'doc' || filetype == 'docx') {
					this.uploadForm.file = file;
					this.uploadForm.uploadFile = file.name;
					return
					this.uploadForm.uploadFlag = true;
					this.uploadForm.uploadPress = 0;
					const key = `szhjxpt/topics/${file.name}`;
					putProgress(key, file, ((progress) => {
						this.uploadForm.uploadPress = parseInt(progress * 100);
					})).then(res => {
						this.uploadForm.uploadPress = 100;
						this.uploadForm.uploadFlag = false;
						this.uploadForm.file = this.baseurl + key;
					})
				} else {
					this.$message({
						type: 'error',
						message: '请选择excal文件！'
					})
					this.$refs.upload_folder.value = ''
				}
			},
			handleFileInput(event) {
				if(event.target.files && event.target.files.length > 0) {
					var file = event.target.files[0];
					this.handleFileUpload(file)
				}
			},
			handleFileDrop(event) {
				this.stopEvent(event);
				if(event.dataTransfer.files && event.dataTransfer.files.length > 0) {
					var file = event.dataTransfer.files[0];
					console.log(file)
					this.handleFileUpload(file)
				}
			},
			clickElement(event, el) {
				event.stopPropagation();
				this.$refs[el].click();
			},
			dragenter(event) {
				this.stopEvent(event);
				this.dragenterIng = true;
			},
			dragleave(event) {
				this.stopEvent(event);
				this.dragenterIng = false;
			},
			stopEvent(event) {
				event.stopPropagation();
				event.preventDefault();
			},
			selectUpType(questionUse) {
				this.uploadForm.questionUse = questionUse;
			},
			beforeCheck() {
				if(this.postData) {
					return
				}
				this.postData = true;
				setTimeout(() => {
					this.postData = false;
				}, 1000)
				this.$refs.addForm.validate(valid => {
					if(valid) {
						this.$refs.questioninput.beforeCheck().then((resdata) => {
							var data = Object.assign({}, this.addForm, resdata);
							if(this.topicId) {
								data.topicId = this.topicId
								updateTopic(data).then(res => {
									if(res.code == '200') {
										this.$message({
											type: 'success',
											message: res.message
										})
										this.clearCheck(true);
										this.currentChange(1);
									} else {
										this.$message({
											type: 'error',
											message: res.message
										})
									}
								})
							} else {
								saveTopic(data).then(res => {
									if(res.code == '200') {
										this.$message({
											type: 'success',
											message: res.message
										})
										this.clearCheck(true);
										this.currentChange(1);
									} else {
										this.$message({
											type: 'error',
											message: res.message
										})
									}
								})
							}
						}).catch((err) => {
							this.$message({
								type: 'error',
								message: "试题有内容未填写"
							})
						})
					} else {
						this.$message({
							type: 'error',
							message: "试题有内容未填写"
						})
					}
				});
			},
			clearCheck(flag) {
				this.topicId = '';
				this.addForm.majorId = '';
				this.addForm.questionUse = '';
				this.addForm.questionType = '';
				this.addForm.difficulty = '';
				this.$nextTick(() => {
					this.$refs.questioninput.clearCheck();
					this.$refs.addForm.clearValidate();
					if(flag) {
						this.addShow = false;
					}
				})
			},
			selectType(questionUse) {
				this.addForm.questionUse = questionUse;
			},
			openEdit(topic) {
				selectTopicDetail({
					topicId: topic.topicId
				}).then(res => {
					topic
					this.addForm = Object.assign({}, this.addForm, topic, res.data);
					this.topicId = topic.topicId;
					this.addShow = true;
				})
			},
			openInfo(topic) {
				selectTopicDetail({
					topicId: topic.topicId
				}).then(res => {
					this.openTopic = Object.assign({}, topic, res.data);
					this.topicShow = true;
				})
			},
			openDelete(topic) {
				this.$confirm('是否删除该试题?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					removeTopic({
						topicId: topic.topicId
					}).then(async res => {
						if(res.code == '200') {
							this.$message({
								message: '删除成功',
								type: 'success'
							})
							this.currentChange(1);
						} else {
							this.$message({
								message: res.message,
								type: 'error'
							})
						}
					})
				}).catch(() => {});
			},
			openDown() {
				topicExport(this.searchForm)
			},
			reGet() {
				this.searchForm.question = '';
				this.searchForm.questionType = '';
				this.searchForm.difficulty = '';
				this.searchForm.questionUse = '';
				this.searchForm.majorId = '';
				this.searchForm.orderBy = 'updateTime';
				this.searchForm.ascDesc = 'desc';
				this.currentChange(1);
			},
			sortChange(data) {
				this.searchForm.orderBy = data.prop;
				this.searchForm.ascDesc = data.order == "descending" ? "desc" : "asc";
				this.currentChange(1);
			},
			currentChange(pageNum) {
				this.searchForm.pageNum = pageNum;
				this.getDataList();
			},
			getDataList() {
				topicList(this.searchForm).then(async res => {
					this.dataList = res.data.list;
					this.searchForm.total = res.data.total;
				})
			},
			getMajors() {
				majorList().then(res => {
					this.majors = res.data
				})
			},
			getinfo() {
				teacherInfo().then(res => {
					if(res.code == '200') {
						this.userinfo = res.data;
						this.getDataList()
					}
				})
			},
		},
	}
</script>